<template>
    <div class="mine-shopsettle-edit-wrap">
        <van-nav-bar title="发布商品" left-arrow fixed @click-left="onClickLeft" />

        <div class="image-title">
            商品封面图
        </div>
        <div class="upload-ul">
            <van-uploader v-model="cover_url" :max-count="1" :after-read="afterCoverReadFront"
                :before-delete="uploadCoverDleteFront" />
        </div>

        <div class="image-title">
            商品图
        </div>
        <div class="upload-ul">
            <van-uploader v-model="photo_albums" :max-count="8" :after-read="afterPhotoReadFront"
                :before-delete="uploadPhotoDleteFront" />
            <div class="upload-ul-title">8张主图尺寸一致</div>
            <div class="upload-ul-tips">上传高清优质图片，否则审核会比驳回</div>
        </div>
        <div class="image-title">
            商品标题
        </div>
        <div class="input-wrap">
            <van-field v-model="message" rows="2" autosize label="" type="textarea" maxlength="40"
                placeholder="最多输入40字符" show-word-limit />
        </div>
        <div>
            <van-field required v-model="mccName" label="类目" placeholder="选择类目，确认商品信息"  @click="showMcc = true" readonly is-link input-align="right" />
            <van-field required v-model="skuName" label="规格" placeholder="请选择规格" readonly is-link input-align="right" @click="handleToSku"/>
            <van-field required v-model="price" label="价格" placeholder="请输入价格"  input-align="right" />
            <van-field required v-model="score" label="库存" placeholder="请输入库存"   input-align="right" />
            <van-field required v-model="fee" label="让利比例" placeholder="请选择让利比例" readonly is-link input-align="right" />
        </div>


        <div class="image-title">
            图文描述
        </div>
        <div class="good-ul">
            <van-uploader v-model="goodImg" :max-count="8" :after-read="afterGoodReadFront"
                :before-delete="uploadGoodDleteFront" />
            <!-- <div v-for="(item, index) in goodList" :key="index" class="good-li">
                <img class="good-li-img" :src="item.cover_url">
                <div class="good-li-name">{{ item.name }}</div>
                <div @click="handleToDelete(item)" class="van-uploader__preview-delete">
                    <i class="van-icon van-icon-cross van-uploader__preview-delete-icon"></i>
                </div>
            </div>
            <div @click="showGoodPopup = true" class="good-upload">
                <i class="van-icon van-icon-photograph van-uploader__upload-icon"></i>
            </div> -->
        </div>






        <div @click="handleToSave" class="save-btn active-btn">保存</div>



        <van-popup v-model="showStartPopup" position="bottom">
            <van-datetime-picker v-model="timeStart" type="time" title="选择开始时间" :min-hour="0" :max-hour="24"
                @confirm="showStartPopup = false" @cancel="showStartPopup = false" />
        </van-popup>

        <van-popup v-model="showEndPopup" position="bottom">
            <van-datetime-picker v-model="timeEnd" type="time" title="选择结束时间" :min-hour="0" :max-hour="24"
                @confirm="showEndPopup = false" @cancel="showEndPopup = false" />
        </van-popup>

        <van-popup v-model="showGoodPopup" position="center" round closeable>
            <div class="good-box">
                <van-uploader v-model="goodImg" :max-count="1" :after-read="afterGoodReadFront"
                    :before-delete="uploadGoodDleteFront" />

                <input class="good-input" placeholder="跟大家介绍下这个商品吧（15字内）" type="text" v-model="goodName" />
                <div @click="handleToGoodUpload" class="good-save-btn">完成</div>
            </div>

        </van-popup>
        <van-popup v-model="showMcc" position="bottom">
      <!-- <van-area :area-list="mccList" @confirm="onConfirmMcc" @cancel="showMcc = false" /> -->
      <van-cascader
        :field-names="fieldNames"
        v-model="cascaderValueMcc"
        title="请选择店铺类型"
        :options="optionsMcc"
        @close="showMcc = false"
        @finish="onFinishMcc"
      />
    </van-popup>

    </div>
</template>

<script>
import { getOssParams, uploadImage, uploadDelete } from "@/api/upload";
import { CATE_LIST } from "@/api/mine";
export default {
    data() {
        return {
            id: this.$route.query.id,
            shopInfo: null,

            // 封面
            cover_url: [],

            // 店铺展示图
            photo_albums: [],

            // 商品列表
            goodList: [],
            goodImg: [],
            goodName: '',

            timeStart: '',
            timeEnd: '',

            showStartPopup: false,
            showEndPopup: false,
            showGoodPopup: false,

            message: '',
            showMcc:false,
            mccName:'',
            fieldNames: {
        text: "name",
        value: "id",
        children: "children",
      },
      cascaderValueMcc:'',
      optionsMcc:[],
      price:"",
      skuName:"",
      score:"",
      fee:""
        }
    },
    created() {
     // this.getShopInfo();
      let params=JSON.parse(localStorage.getItem('releaseData'))
      if(params){
        this.mccName=params.mccName
      }
        // 商品列表
        // this.getGoodList();
        this.fetchRegionsMcc()
    },
    methods: {
        onClickLeft() {
            this.$router.back()
        },

        // 门店详情
        getShopInfo() {
            this.$http.get(`/store/manage/${this.id}/info`)
                .then(res => {
                    this.shopInfo = res.data;

                    this.timeStart = res.data.business_time.split(' ~ ')[0];
                    this.timeEnd = res.data.business_time.split(' ~ ')[1];

                    this.cover_url = [{
                        url: this.shopInfo.cover_url
                    }]

                    let photo_albums = this.shopInfo.photo_albums.split(',');
                    photo_albums.forEach(item => {
                        this.photo_albums.push({
                            url: item
                        })
                    })

                })
        },
        // 商品列表
        getGoodList() {
            this.$http.get(`/store/manage/${this.id}/product_list`)
                .then(res => {
                    this.goodList = res.data;
                })
        },
            // 经营类目
    async fetchRegionsMcc(parentCode, level) {
        //
      const res = await this.$http.get(CATE_LIST);
      this.optionsMcc = res.data;
    },
    // 确定类目
    onFinishMcc({ selectedOptions }) {
      this.showMcc = false;

      this.selectMccList = selectedOptions;

      selectedOptions = selectedOptions.filter((item) => {
        return item.value !== 0;
      });

    //   console.log(selectedOptions, "333");

      this.mccName = selectedOptions.map((option) => option.name).join("/");
    },
    handleToSku(){
        let data={
            mccName:this.mccName,
            skuName:this.skuName,
            price:this.price,
            score:this.score,
            fee:this.fee
        }
        localStorage.setItem('releaseData',JSON.stringify(data))
        this.$router.push({
            path:'/merchantSku',
        })
    },  
        // 上传封面正面
        async afterCoverReadFront(file) {
            try {
                this.ossParams = await getOssParams(this.$http);
                // 调用封装的上传函数
                await uploadImage(file, this.ossParams, this.cover_url);

                this.cover_url = this.cover_url.filter(item => {
                    return item.url
                })

            } catch (error) {
                console.error('处理上传错误:', error);
            }
        },
        // 删除
        uploadCoverDleteFront(file) {
            this.cover_url = uploadDelete(file, this.cover_url);
        },

        // 上传店铺正面
        async afterPhotoReadFront(file) {
            try {
                this.ossParams = await getOssParams(this.$http);

                // 调用封装的上传函数
                await uploadImage(file, this.ossParams, this.photo_albums);

                this.photo_albums = this.photo_albums.filter(item => {
                    return item.url
                })

            } catch (error) {
                console.error('处理上传错误:', error);
            }
        },
        // 删除
        uploadPhotoDleteFront(file) {
            this.photo_albums = uploadDelete(file, this.photo_albums);
        },
        // 上传封面正面
        async afterGoodReadFront(file) {
            try {
                this.ossParams = await getOssParams(this.$http);
                // 调用封装的上传函数
                await uploadImage(file, this.ossParams, this.goodImg);

                this.goodImg = this.goodImg.filter(item => {
                    return item.url
                })

            } catch (error) {
                console.error('处理上传错误:', error);
            }
        },
        // 删除
        uploadGoodDleteFront(file) {
            this.goodImg = uploadDelete(file, this.goodImg);
        },
        // 商品删除
        handleToDelete(item) {
            this.$http.delete(`/store/manage/${this.id}/product_delete/${item.id}`)
                .then(() => {

                    this.getGoodList();
                })
        },
        // 商品上传
        handleToGoodUpload() {
            if (!this.goodImg.length) {
                this.$toast('请上传商品图片')
                return
            }
            if (!this.goodName.trim()) {
                this.$toast('请输入商品名称')
                return
            }

            let params = {};
            params['id'] = 0;
            params['name'] = this.goodName;

            // 封面图片
            let goodImg = [];
            this.goodImg.forEach(item => {
                goodImg.push(item.url)
            })

            params['cover_url'] = goodImg.join(',');

            this.$http.post(`/store/manage/${this.id}/product_submit`, params)
                .then(res => {
                    this.showGoodPopup = false;
                    this.goodImg = [];
                    this.goodName = '';
                    this.getGoodList();
                })
        },
        // 保存
        handleToSave() {
            localStorage.removeItem('releaseData')
            return
            if (!this.cover_url.length) {
                this.$toast('请上传门店门头照')
                return
            }
            if (!this.photo_albums.length) {
                this.$toast('请上传门店展示照片')
                return
            }
            if (!this.goodList.length) {
                this.$toast('请上传门店商品照片')
                return
            }

            let params = {};
            params['id'] = this.id;

            // 封面图片
            let cover_url = [];
            this.cover_url.forEach(item => {
                cover_url.push(item.url)
            })

            params['cover_url'] = cover_url.join(',');

            // 店铺展示图片
            let photo_albums = [];
            this.photo_albums.forEach(item => {
                photo_albums.push(item.url)
            })

            console.log(this.photo_albums, '99')

            params['photo_albums'] = photo_albums.join(',');

            params['business_time'] = `${this.timeStart} ~ ${this.timeEnd}`;
            params['gift'] = this.shopInfo.gift;

            this.$http.post('/store/manage/update', params)
                .then(() => {
                    this.$toast.success('保存成功');

                    setTimeout(() => {
                        this.$router.back()
                    }, 500)
                })
        }

    }
}
</script>

<style lang="scss">
.mine-shopsettle-edit-wrap {
    min-height: 100vh;
    padding-top: 46px;
    padding-bottom: calc(1.8rem + constant(safe-area-inset-bottom));
    padding-bottom: calc(1.8rem + env(safe-area-inset-bottom));
    background-color: #FFFFFF;
    box-sizing: border-box;

    .van-nav-bar .van-icon {
        color: #333333;
    }

    .van-nav-bar__arrow {
        font-size: 20px;
    }

    .van-hairline--bottom::after {
        display: none;
    }

    .basic-title {
        padding: 0.24rem 0.32rem 0.16rem;
        font-size: 0.28rem;
        font-weight: 500;
        color: #333333;
    }

    .shop-ceil {
        display: flex;
        justify-content: space-between;
        font-size: 0.28rem;
        padding: 0.32rem;
        color: #333333;
        border-bottom: 0.02rem solid #ededed;

        .shop-ceil-label {
            &::before {
                content: '*';
                font-size: 0.28rem;
                color: #F9301B;
            }
        }

        .shop-ceil-val {
            max-width: 5rem;
        }
    }

    .save-btn {
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0.24rem;
        bottom: calc(0.24rem + constant(safe-area-inset-bottom));
        bottom: calc(0.24rem + env(safe-area-inset-bottom));
        margin: auto;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 6.06rem;
        height: 0.88rem;
        margin: auto;
        font-size: 0.32rem;
        font-weight: 500;
        color: #FFFFFF;
        border-radius: 0.44rem;
        background: linear-gradient(135deg, #FF5851 0%, #E9011B 100%);
    }

    .basic-subsity-title {
        font-weight: 500;
        font-size: 0.28rem;
        padding: 0.32rem 0.32rem 0.24rem;
        color: #333333;
    }

    .gift-box {
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 6.86rem;
        height: 0.88rem;
        margin: auto;
        padding: 0 0.24rem;
        background: #F2F4F5;
        border-radius: 0.16rem;
        box-sizing: border-box;

        .gift-input {
            width: 5.6rem;
            font-size: 0.28rem;
            border: none;
            background-color: transparent;
        }

        .gift-max-len {
            font-size: 0.24rem;
            color: #999999;
        }
    }

    .gift-demo {
        height: 0.34rem;
        margin-top: 0.12rem;
        padding-left: 0.32rem;
        line-height: 0.34rem;
        font-size: 0.24rem;
        color: #F9301B;
    }

    .basic-shop-title {
        height: 0.4rem;
        padding-left: 0.32rem;
        margin-top: 0.32rem;
        line-height: 0.4rem;
        font-size: 0.28rem;
        font-weight: 500;
        color: #333333;
    }

    .image-title {
        height: 0.4rem;
        padding-top: 0.28rem;
        padding-bottom: 0.2rem;
        padding-left: 0.32rem;
        line-height: 0.4rem;
        font-size: 0.28rem;
        font-weight: 400;
        color: #333333;

        &::before {
            content: '*';
            font-size: 0.28rem;
            color: #F9301B;
        }
    }

    .upload-ul {
        padding: 0 0.32rem;
    }

    .shop-time {
        display: flex;
        align-items: center;

        .shop-time-start {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 1.08rem;
            height: 0.48rem;
            margin-right: 0.12rem;
            border: 1px solid #c1c1c1;
        }

        .shop-time-end {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 1.08rem;
            height: 0.48rem;
            margin-left: 0.12rem;
            border: 1px solid #c1c1c1;
        }
    }

    .good-ul {
        display: flex;
        flex-wrap: wrap;
        padding: 0 0.32rem;


        .good-li {
            position: relative;
            width: 80px;
            height: 80px;
            margin: 0 8px 8px 0;
        }

        .good-li-img {
            width: 80px;
            height: 80px;
            object-fit: cover;
        }

        .good-li-name {
            height: 0.4rem;
            line-height: 0.4rem;
            font-size: 0.24rem;
            text-align: center;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            word-break: break-all;
        }
    }

    .good-upload {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 80px;
        height: 80px;
        background-color: #f7f8fa;
    }

    .good-box {
        display: flex;
        align-items: center;
        flex-direction: column;
        width: 5rem;
        padding: 0.32rem;
        padding-top: 0.6rem;

        .good-input {
            height: 0.6rem;
            width: 4rem;
            color: #333333;
            font-size: 0.24rem;
            margin-top: 0.2rem;
            padding: 0 0.32rem;
            border: 1px solid #ededed;
        }
    }

    .good-save-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 0.6rem;
        width: 2rem;
        font-size: 0.28rem;
        color: #FFFFFF;
        margin-top: 0.2rem;
        border-radius: 0.3rem;
        background: linear-gradient(135deg, #FF5851 0%, #E9011B 100%);
    }
}

.upload-ul-title {
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: .24rem;
    color: #333333;
    line-height: .34rem;
    text-align: left;
    font-style: normal;
}

.upload-ul-tips {
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: .2rem;
    color: #666666;
    line-height: .28rem;
    text-align: left;
    font-style: normal;
    margin-top: .1rem;
}

.input-wrap {
    width: 95%;
    margin: 0 auto;

    .van-cell {
        background: #F2F4F5;
        border-radius: .2rem;
    }
}
</style>
